package org.echo.storage.impl;

import com.sun.org.apache.xpath.internal.SourceTree;
import org.echo.storage.Storage;
import org.echo.storage.StorageConfig;
import org.echo.util.SymbolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;

@Service
public class LocalStorage implements Storage {

    @Autowired
    private StorageConfig config;

    @Override
    public void download(String url, String name) {
        // 下载网络文件
        int bytesum = 0;
        int byteread;

        DecimalFormat df = new DecimalFormat("#.000");

        String fileName = "";

        try {
            URL url2 = new URL(url);

            String extension = url.substring(url.lastIndexOf("."));
            extension = extension.substring(0, extension.lastIndexOf("?"));

            URLConnection conn = url2.openConnection();
            InputStream inStream = conn.getInputStream();

            fileName = SymbolUtil.clear(name) + extension;

            FileOutputStream fs = new FileOutputStream(config.getTargetPath() + fileName);

            int totalSize = conn.getContentLength();

            System.out.println("开始下载:" + fileName);

            byte[] buffer = new byte[1204];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;

                if(config.getShowProcess()){
                    System.out.print(bytesum);
                    System.out.print(":");
                    System.out.println(totalSize);
                }

                if(config.getShowPercent()){
                    Double t1 = Double.valueOf(bytesum);
                    Double t2 = Double.valueOf(totalSize);
                    Double percent = Double.parseDouble(df.format(t1/t2)) * 100;
                    System.out.println(percent + "%");
                }

                fs.write(buffer, 0, byteread);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("完成下载:" + fileName);
    }

}
